from aip import AipOcr
import pandas as pd
import os
import glob
import json

# APP_ID = '29102474'
# API_KEY = '8f4dflL11V2dIIzBZrLmYIrd'
# SECRET_KEY = 'N1p3V9zmNxxGKwPp6Bh0lGk6aVsSwmWp'
# client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


def get_paths(folder_path):
    # 指定支持的图片格式
    image_extensions = ('*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp')

    # 使用glob模块来获取所有这些扩展名的文件路径
    image_paths = []
    for ext in image_extensions:
        image_paths.extend(glob.glob(os.path.join(folder_path, ext)))

    return image_paths

def get_image_paths(folder_path):
    if not os.path.exists(folder_path):
        raise ValueError("Invalid folder path")
    # 获取所有图片的绝对路径
    image_paths = [os.path.abspath(path) for path in get_paths(folder_path)]
    return image_paths


def function1(folder_path,dir): # folder_path:图片文件夹路径
    try:
        json_path=os.path.join(dir,'baidu.json')
        df_json=pd.read_json(json_path)
        if len(df_json) == 0:
            return '错误提示: 请先设置百度OCR的APP_ID、API_KEY、SECRET_KEY'
        image_path_list = get_image_paths(folder_path)  # 获取图片路径
        if len(image_path_list) == 0:
            return '错误提示: 文件夹中没有图片文件'
        df = pd.DataFrame()
        i = 0
        APP_ID = str(df_json.iloc[0,0])
        API_KEY = df_json.iloc[0,1]
        SECRET_KEY = df_json.iloc[0,2]
        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
        for image_path in image_path_list:
            i = i + 1
            with open(image_path, 'rb') as image_file:
                content = image_file.read()
            response = client.basicGeneral(content)
            # 判断是否识别成功
            if response:
                # 提取words_result部分
                words_result = [result['words'] for result in response['words_result']]
                cname = 'image' + str(i)
                df[cname] = pd.DataFrame(words_result)
        # 将DataFrame转换为字典列表
        dict_list = df.to_dict(orient='records')

        # 将字典列表转换为指定格式的JSON字符串
        json_data = json.dumps(dict_list)

        return json_data
    except Exception as e:
        return "错误提示: "+str(e)


